package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.PigeonStatusBean
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityBreedingTrackingBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterBreedingTracking
import com.gexiaobao.pigeon.ui.adapter.AddBloodPigeonPopAdapter
import com.gexiaobao.pigeon.ui.dialog.RxInputCustomDialog
import com.gexiaobao.pigeon.ui.dialog.RxInputRingDialog
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/9/4 11:28
 * @Describe    : 作育跟踪
 */
class ActivityBreedingTracking : BaseActivity<BreedingPigeonViewModel, ActivityBreedingTrackingBinding>() {

    private val mAdapter: AdapterBreedingTracking by lazy { AdapterBreedingTracking(arrayListOf()) }
    private var breedingPairId = 0
    private var mBreedingPairSubId = ""

    private val popWindow: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var adapterStatus: AddBloodPigeonPopAdapter? = null
    private var mListStatus: ArrayList<String> = arrayListOf()
    private var mList: ArrayList<PigeonStatusBean> = arrayListOf()
    private var mAdapterPosition = -1

    private var mDate = ""
    private var mStatus = 0
    private var mId = 0
    private var mFemaleId = 0
    private var mMaleId = 0
    private var mRingOne = ""
    private var mRingTwo = ""
    private var mRemark = ""

    private var trackId = 0
    private var trackPairTime = ""
    private var trackNestBox = ""
    private var trackFemaleNanny = ""
    private var trackMaleNanny = ""
    private var trackNannyNestBox = ""
    private var trackRemark = ""
    private var isOnBoardShow = false

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeBar.tvTitle.text = "作育跟踪"
        mDatabind.includeBar.tvRightMenu.isVisible = true
        mDatabind.includeBar.tvRightMenu.text = "设置提醒"
        mDatabind.tvPairDate.text = DatetimeUtil.getTimeStringYear2()

        mFemaleId = intent.getIntExtra("femaleId", 0)
        mMaleId = intent.getIntExtra("maleId", 0)

        breedingPairId = intent.getIntExtra("pairId", 0)
        if (intent.hasExtra("breedingPairSubId")) {
            mDatabind.recyclerView.isVisible = true
            mDatabind.btnRearInfo.isVisible = false
            mBreedingPairSubId = intent.getStringExtra("breedingPairSubId").toString()
            mViewModel.getBreedingPairTimeAxisInfo(mBreedingPairSubId)
            mViewModel.getBreedingPairSubInfo(mBreedingPairSubId.toInt())
        } else {
            mDatabind.recyclerView.isVisible = false
            mDatabind.btnRearInfo.isVisible = true
        }
        val maleName = intent.getStringExtra("maleName").toString().trim()
        val femaleName = intent.getStringExtra("femaleName").toString().trim()
        val maleRingId = intent.getStringExtra("maleRingId").toString().trim()
        val femaleRingId = intent.getStringExtra("femaleRingId").toString().trim()
        mDatabind.tvTrackMaleName.text = maleName
        mDatabind.tvTrackFemaleName.text = femaleName
        mDatabind.tvMaleRingId.text = maleRingId
        mDatabind.tvFemaleRingId.text = femaleRingId

        mDatabind.recyclerView.init(LinearLayoutManager(this), mAdapter)

        mAdapter.addChildClickViewIds(R.id.tvEggStatus, R.id.ivArrowDown, R.id.llChooseTime, R.id.tvEditRemark)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            mId = mAdapter.data[position].id
            mDate = mAdapter.data[position].date
            mRemark = mAdapter.data[position].remark
            mAdapterPosition = position
            when (view.id) {
                R.id.tvEggStatus, R.id.ivArrowDown -> setEggStatusPopList(view, mAdapter.data[position].list)
                R.id.llChooseTime -> chooseDate(2)
                R.id.tvEditRemark -> showDialogEditRemark(position)

            }
        }

        mAdapter.setOnRingClickListener(object : AdapterBreedingTracking.OnRingItemClickListener {
            override fun onRingItemClick(positionP: Int, position: Int, id: Int, ringNumber: String) {
                mId = mAdapter.data[positionP].id
                if (position == 0) {
                    mStatus = id
                } else if (position == 1) {
                    mStatus = id
                }
                showInputRingDialog(position, ringNumber)
            }
        })

        popWindow.setOnItemClickListener { _, _, position, _ ->
            popWindow.dismiss()
            mStatus = mList[position].id
            editBreedingPairTimeAxisInfo()
        }

        /** 监听软键盘的显示和隐藏 */
        setupKeyboardVisibilityListener()

        eventViewModel.toRefreshData.observeInActivity(this) {
            if (mBreedingPairSubId.isNotEmpty()) {
                mViewModel.getBreedingPairSubInfo(mBreedingPairSubId.toInt())
            }
        }
    }

    private fun setupKeyboardVisibilityListener() {
        val rootView = findViewById<View>(android.R.id.content)
        rootView.viewTreeObserver.addOnGlobalLayoutListener {
            val rect = Rect()
            rootView.getWindowVisibleDisplayFrame(rect)
            val screenHeight = rootView.height
            val keypadHeight = screenHeight - rect.bottom

            if (keypadHeight > screenHeight * 0.15) {
                // 键盘可见
                onKeyboardShown()
            } else {
                // 键盘隐藏
                onKeyboardHidden()
            }
        }
    }

    private fun onKeyboardShown() {
        isOnBoardShow = true
    }

    private fun onKeyboardHidden() {
        trackNestBox = mDatabind.etTrackPairNestBox.text.toString().trim()
        trackFemaleNanny = mDatabind.etTrackFemaleSitter.text.toString().trim()
        trackMaleNanny = mDatabind.etTrackMaleSitter.text.toString().trim()
        trackNannyNestBox = mDatabind.etTrackNestBox.text.toString().trim()
        trackRemark = mDatabind.etTrackRemarkInfo.text.toString().trim()
        if (isOnBoardShow) editTrackInfo()
        isOnBoardShow = false
    }

    private fun editBreedingPairTimeAxisInfo() {
        showLoading(getString(R.string.loading))
        mViewModel.editBreedingPairTimeAxisInfo(mId, mDate, mStatus, mRingOne, mRingTwo, mRemark)
    }

    private fun showInputRingDialog(position: Int, ringId: String) {
        val dialog = RxInputRingDialog(this)
        dialog.setRingData(ringId)
        dialog.setSureListener {
            val result = dialog.getContent()
            if (result.isEmpty()) {
                return@setSureListener
            }
            if (position == 0) {
                mRingOne = result
            } else if (position == 1) {
                mRingTwo = result
            }
            editBreedingPairTimeAxisInfo()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showDialogEditRemark(position: Int) {
        mRingOne = mAdapter.data[position].ringList[0].ringId
        mRingTwo = mAdapter.data[position].ringList[1].ringId
        val dialog = RxInputCustomDialog(this)
        dialog.setTitle("备注")
        dialog.setHintText("最多可输入12个字符")
        dialog.setSureListener {
            val remark = dialog.getContent()
            if (remark.isEmpty()) {
                RxToast.warning("请输入备注信息")
                return@setSureListener
            }
            mRemark = dialog.getContent()
            editBreedingPairTimeAxisInfo()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun setEggStatusPopList(view: View, list: ArrayList<PigeonStatusBean>) {
        if (list.isNotEmpty()) {
            mList.clear()
            mList.addAll(list)
            mListStatus.clear()
            list.forEach {
                mListStatus.add(it.info)
            }
        }
        adapterStatus = AddBloodPigeonPopAdapter(this, mListStatus)
        popWindow.setAdapter(adapterStatus)
        popWindow.anchorView = view//设置ListPopupWindow的锚点，关联mButton位置
        popWindow.width = LinearLayout.LayoutParams.MATCH_PARENT
        popWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindow.isModal = true
        popWindow.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 修改作育记录信息 */
        mViewModel.editBreedingPairSubInfoResult.observe(this) {
            eventViewModel.toRefreshData.value = true
            mViewModel.getBreedingPairSubInfo(mBreedingPairSubId.toInt())
        }
        /** 修改作育跟踪时间轴信息 */
        mViewModel.editTimeAxisResult.observe(this) {
            mViewModel.getBreedingPairTimeAxisInfo(mBreedingPairSubId)
        }
        /** 获取作育跟踪 */
        mViewModel.getBreedingPairSubInfoResult.observe(this) {
            mDatabind.data = it
            trackId = it.id
            trackPairTime = it.pairTime
            trackNestBox = it.nestBox
            trackFemaleNanny = it.femaleNanny
            trackMaleNanny = it.maleNanny
            trackNannyNestBox = it.nannyNestBox
            trackRemark = it.remark
            mDatabind.tvTrackMaleName.text = it.maleName
            mDatabind.tvTrackFemaleName.text = it.femaleName
            mDatabind.tvMaleRingId.text = it.maleRing
            mDatabind.tvFemaleRingId.text = it.femaleRing
            if (it.pairTime.isNotEmpty()) {
                mDatabind.tvPairDate.text = it.pairTime
            }
        }
        /** 获取作育跟踪时间轴 */
        mViewModel.getBreedingPairTimeAxisResult.observe(this) {
            mDatabind.recyclerView.isVisible = true
            mAdapter.setList(it.list)
            mAdapter.notifyDataSetChanged()
        }
        /** 保存作育跟踪 */
        mViewModel.addBreedingPairSubResult.observe(this) {
            mBreedingPairSubId = it.breedingPairSubId.toString()
            mViewModel.getBreedingPairTimeAxisInfo(mBreedingPairSubId)
            mDatabind.btnRearInfo.isVisible = false
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.includeBar.tvRightMenu,
            mDatabind.tvPairDate,
            mDatabind.btnRearInfo,
            mDatabind.conBreedingTrackMale,
            mDatabind.conBreedingTrackFemale
        ) {
            when (it) {
                mDatabind.conBreedingTrackFemale -> startToPigeonBaseInfo(mFemaleId)
                mDatabind.conBreedingTrackMale -> startToPigeonBaseInfo(mMaleId)
                mDatabind.btnRearInfo -> addBreedingTrackSub()
                mDatabind.tvPairDate -> chooseDate(1)
                mDatabind.includeBar.tvRightMenu -> startActivity<ActivitySetReindeer>()
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun startToPigeonBaseInfo(mId: Int) {
        if (mId == 0) {
            showMessage("该赛鸽已被删除，无法查看详细信息")
            return
        }
        startActivity<ActivityBloodPigeonInfo>("pigeonId" to mId, "isAmend" to false)
    }

    private fun addBreedingTrackSub() {
        val pairDate = mDatabind.tvPairDate.text.toString().trim()
        if (pairDate.isEmpty()) {
            RxToast.warning("请选择配对时间")
            return
        }
        val map = mapOf(
            "breedingPairId" to breedingPairId,
            "pairTime" to pairDate,
            "nestBox" to mDatabind.etTrackPairNestBox.text.toString().trim(),
            "femaleNanny" to mDatabind.etTrackFemaleSitter.text.toString().trim(),
            "maleNanny" to mDatabind.etTrackMaleSitter.text.toString().trim(),
            "nannyNestBox" to mDatabind.etTrackNestBox.text.toString().trim(),
            "remark" to mDatabind.etTrackRemarkInfo.text.toString().trim()
        )
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        showLoading(getString(R.string.loading))
        mViewModel.addBreedingPairSubInfo(body)
    }

    private fun chooseDate(type: Int) {
        val displayList: MutableList<Int> = mutableListOf()
        displayList.add(DateTimeConfig.YEAR)
        displayList.add(DateTimeConfig.MONTH)
        displayList.add(DateTimeConfig.DAY)
        val dialog = CardDatePickerDialog.builder(this)
            .setTitle("选择日期")
            .setDisplayType(displayList)
            .setBackGroundModel(CardDatePickerDialog.STACK)
            .showBackNow(false)//是否显示一键回到今日 和 定位到今天的日期
            .setPickerLayout(0)
            .setTouchHideable(true)
            .setChooseDateModel(DateTimeConfig.DATE_LUNAR)
            .setWrapSelectorWheel(false)
            .setThemeColor(Color.parseColor("#FF8000"))
            .showDateLabel(false)
            .showFocusDateInfo(false)
            .setOnChoose("选择") {
                if (type == 1) {
                    trackPairTime = DatetimeUtil.conversionTime(it, "yyyy-MM-dd")
                    mDatabind.tvPairDate.text = trackPairTime
                    editTrackInfo()
                } else {
                    mDate = DatetimeUtil.conversionTime(it, "yyyy-MM-dd")
                    editBreedingPairTimeAxisInfo()
                }
            }
            .setOnCancel("关闭") {
            }.build()

        dialog.show()
        /**
         * 重点 需要在dialog show 方法后
         * 得到 BottomSheetDialog 实体，设置其 isHideable 为 false
         */
        (dialog as BottomSheetDialog).behavior.isHideable = false
    }

    private fun editTrackInfo() {
        showLoading(getString(R.string.loading))
        mViewModel.editBreedingPairSubInfo(trackId, trackPairTime, trackNestBox, trackFemaleNanny, trackMaleNanny, trackNannyNestBox, trackRemark)
    }
}